class DataFile < ActiveRecord::Base
    
    attr_accessible :path, :mime_type, :file_size, :created_by, :updated_by
    
    # Relationships:
    belongs_to :document
	
	# Validations:
	validates :path, presence: true
    
    def self.save_files(files, document)
        files.map { |file| save(file, document) }
    end
	
    def self.save(upload, document)
        FileUtils.mkdir_p(document.storage_path, mode: 0555)
        dest_path = File.join(document.storage_path, upload.original_filename)
        
		FileUtils.cp(upload.tempfile, dest_path) 
        file = File.new(dest_path)
		file.chmod(0777)
		
		file
    end
    
    def icon
        case self.mime_type
            when /^image/
                'document/img_icon.png'
            when /^video/
                'document/mov_icon.png'
                
            when 'text/plain'
                'document/txt_icon.png'
            when 'text/richtext'
                'document/txt_icon.png'
            when 'text/rtf'
                'document/txt_icon.png'
            when 'text/html'
                'document/html_icon.png'
            when 'text/css'
                'document/css_icon.png'
				
            when /^audio/
                'document/audio_icon.png'
            when /(zip|compressed)/
                'document/zip_icon.png'
            when 'application/msword'
                'document/word_icon.png'
            when 'application/mspowerpoint'
                'document/ppt_icon.png'
            when 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
                'document/ppt_icon.png'
            when 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                'document/word_icon.png'
            when 'application/octet-stream'
                'document/exe_icon.png'
            when 'application/x-shockwave-flash'
                'document/swf_icon.png'
            when 'application/pdf'
                'document/pdf_icon.png'
            else
                'document/file_icon.png'
        end
    end
end
